package com.example.projectmanagement.config;

import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.model.Permission;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.UserRole;
import com.example.projectmanagement.repository.RoleRepository;
import com.example.projectmanagement.repository.PermissionRepository;
import com.example.projectmanagement.repository.UserRepository;
import com.example.projectmanagement.repository.UserRoleRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Component
public class DataInitializer {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private UserRoleRepository userRoleRepository;
    
    @Autowired
    private com.example.projectmanagement.repository.RolePermissionRepository rolePermissionRepository;

    @PostConstruct
    public void init() {
        initRoles();
        initPermissions();
        initAdminUser();
    }

    private void initRoles() {
        if (roleRepository.count() == 0) {
            List<Role> roles = Arrays.asList(
                createRole("ADMIN", "系统管理员"),
                createRole("LECTURER", "讲师"),
                createRole("STUDENT", "学生"),
                createRole("AUDITOR", "审计员")
            );
            
            roleRepository.saveAll(roles);
            System.out.println("初始化角色数据完成");
        }
    }

    private void initPermissions() {
        if (permissionRepository.count() == 0) {
            List<Permission> permissions = Arrays.asList(
                // 用户管理权限
                createPermission("USER_CREATE", "用户管理", "CREATE", "创建用户"),
                createPermission("USER_READ", "用户管理", "READ", "查看用户"),
                createPermission("USER_UPDATE", "用户管理", "UPDATE", "修改用户"),
                createPermission("USER_DELETE", "用户管理", "DELETE", "删除用户"),
                
                // 角色管理权限
                createPermission("ROLE_CREATE", "角色管理", "CREATE", "创建角色"),
                createPermission("ROLE_READ", "角色管理", "READ", "查看角色"),
                createPermission("ROLE_UPDATE", "角色管理", "UPDATE", "修改角色"),
                createPermission("ROLE_DELETE", "角色管理", "DELETE", "删除角色"),
                
                // 权限管理权限
                createPermission("PERMISSION_CREATE", "权限管理", "CREATE", "创建权限"),
                createPermission("PERMISSION_READ", "权限管理", "READ", "查看权限"),
                createPermission("PERMISSION_UPDATE", "权限管理", "UPDATE", "修改权限"),
                createPermission("PERMISSION_DELETE", "权限管理", "DELETE", "删除权限"),
                
                // 课程管理权限
                createPermission("COURSE_CREATE", "课程管理", "CREATE", "创建课程"),
                createPermission("COURSE_READ", "课程管理", "READ", "查看课程"),
                createPermission("COURSE_UPDATE", "课程管理", "UPDATE", "更新课程"),
                createPermission("COURSE_DELETE", "课程管理", "DELETE", "删除课程"),
                createPermission("COURSE_CATEGORY_MANAGE", "课程管理", "UPDATE", "管理课程分类"),
                createPermission("COURSE_TAG_MANAGE", "课程管理", "UPDATE", "管理课程标签"),
                createPermission("COURSE_VIDEO_UPLOAD", "课程管理", "CREATE", "上传课程视频"),
                createPermission("COURSE_VIDEO_ACCESS_CONTROL", "课程管理", "UPDATE", "控制视频访问权限"),
                createPermission("COURSE_VIDEO_APPROVAL", "课程管理", "UPDATE", "审核视频材料")
            );
            
            permissionRepository.saveAll(permissions);
            System.out.println("初始化权限数据完成");
        }
    }
    
    private void initAdminUser() {

        // 为admin用户分配ADMIN角色
        Optional<User> adminUserOpt = userRepository.findByUsername("admin");
        Optional<Role> adminRoleOpt = roleRepository.findByRoleName("ADMIN");

        User adminUser;
        if (adminUserOpt.isEmpty()) {
            // 如果admin用户不存在，则创建
            adminUser = new User();
            adminUser.setUsername("admin");
            adminUser.setPassword("$2a$10$frvpLTZl2pKintIAnVLBCO8t4wCfcqfJg68sOr34TghOxZipUEnPK"); // 明文密码: admin123
            adminUser.setName("管理员");
            adminUser.setPhone("12345678900");
            adminUser.setDepartment("IT部");
            adminUser.setStatus(1);
            adminUser.setCreateTime(LocalDateTime.now());
            adminUser.setUpdateTime(LocalDateTime.now());
            userRepository.save(adminUser);
            System.out.println("创建admin用户完成");
        } else {
            adminUser = adminUserOpt.get();
        }

        if (adminRoleOpt.isPresent()) {
            Role adminRole = adminRoleOpt.get();
            
            // 检查是否已经分配了角色
            if (!userRoleRepository.findByUserAndRole(adminUser, adminRole).isPresent()) {
                UserRole userRole = new UserRole();
                userRole.setUser(adminUser);
                userRole.setRole(adminRole);
                userRoleRepository.save(userRole);
                System.out.println("为admin用户分配ADMIN角色完成");
            }
        }
        
        // 为ADMIN角色分配所有权限
        if (adminRoleOpt.isPresent() && permissionRepository.count() > 0) {
            Role adminRole = adminRoleOpt.get();
            List<Permission> allPermissions = permissionRepository.findAll();
            
            // 检查是否已经分配了权限
            List<com.example.projectmanagement.model.RolePermission> existingRolePermissions = 
                rolePermissionRepository.findByRole(adminRole);
            
            if (existingRolePermissions.isEmpty()) {
                for (Permission permission : allPermissions) {
                    com.example.projectmanagement.model.RolePermission rolePermission = 
                        new com.example.projectmanagement.model.RolePermission();
                    rolePermission.setRole(adminRole);
                    rolePermission.setPermission(permission);
                    rolePermissionRepository.save(rolePermission);
                }
                System.out.println("为ADMIN角色分配所有权限完成");
            }
        }
        
        // 为LECTURER角色分配课程管理权限
        Optional<Role> lecturerRoleOpt = roleRepository.findByRoleName("LECTURER");
        if (lecturerRoleOpt.isPresent() && permissionRepository.count() > 0) {
            Role lecturerRole = lecturerRoleOpt.get();
            List<Permission> lecturerPermissions = Arrays.asList(
                // 课程相关权限
                permissionRepository.findByPermissionCode("COURSE_CREATE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_READ").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_UPDATE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_VIDEO_UPLOAD").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_VIDEO_ACCESS_CONTROL").orElse(null)
            );
            
            // 过滤掉null权限
            lecturerPermissions = lecturerPermissions.stream()
                .filter(p -> p != null)
                .collect(java.util.stream.Collectors.toList());
            
            // 检查是否已经分配了权限
            List<com.example.projectmanagement.model.RolePermission> existingLecturerPermissions = 
                rolePermissionRepository.findByRole(lecturerRole);
            
            if (existingLecturerPermissions.isEmpty()) {
                for (Permission permission : lecturerPermissions) {
                    com.example.projectmanagement.model.RolePermission rolePermission = 
                        new com.example.projectmanagement.model.RolePermission();
                    rolePermission.setRole(lecturerRole);
                    rolePermission.setPermission(permission);
                    rolePermissionRepository.save(rolePermission);
                }
                System.out.println("为LECTURER角色分配课程权限完成");
            }
        }
        
        // 为ADMIN角色分配课程管理权限
        if (adminRoleOpt.isPresent() && permissionRepository.count() > 0) {
            Role adminRole = adminRoleOpt.get();
            List<Permission> adminPermissions = Arrays.asList(
                // 课程相关权限
                permissionRepository.findByPermissionCode("COURSE_CREATE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_READ").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_UPDATE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_DELETE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_CATEGORY_MANAGE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_TAG_MANAGE").orElse(null),
                permissionRepository.findByPermissionCode("COURSE_VIDEO_APPROVAL").orElse(null)
            );
            
            // 过滤掉null权限
            adminPermissions = adminPermissions.stream()
                .filter(p -> p != null)
                .collect(java.util.stream.Collectors.toList());
            
            // 检查是否已经分配了权限
            List<com.example.projectmanagement.model.RolePermission> existingAdminPermissions = 
                rolePermissionRepository.findByRole(adminRole);
            
            if (existingAdminPermissions.isEmpty()) {
                for (Permission permission : adminPermissions) {
                    com.example.projectmanagement.model.RolePermission rolePermission = 
                        new com.example.projectmanagement.model.RolePermission();
                    rolePermission.setRole(adminRole);
                    rolePermission.setPermission(permission);
                    rolePermissionRepository.save(rolePermission);
                }
                System.out.println("为ADMIN角色分配课程管理权限完成");
            }
        }

    }

    private Role createRole(String roleName, String roleDescription) {
        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleDescription(roleDescription);
        return role;
    }

    private Permission createPermission(String permissionCode, String resourceType, String action, String description) {
        Permission permission = new Permission();
        permission.setPermissionCode(permissionCode);
        permission.setPermissionName(permissionCode);
        permission.setResourceType(resourceType);
        permission.setAction(action);
        permission.setDescription(description);
        return permission;
    }
}